/**
 *  \file   sensor.c
 *  \author Miora ANDRIAMANOHARISOA, Loic MINGHETTI
 *  \date   PFE 2011
 **/
 
 
 
#include "include.h"

 
// Average raw temperature table                                                        
static int raw_temp_array[CONF_NUM_AVG_TEMP];  
static void init_raw_temp_array(int temp)  {
	int i;
	for (i = 0; i < CONF_NUM_AVG_TEMP; i++) {
		raw_temp_array[i] = temp;
	}
}
static void add_raw_temp(int temp) {
	static int pos = 0;
	pos = (pos + 1) % CONF_NUM_AVG_TEMP;
	raw_temp_array[pos] = temp;
}
// get average temp 
static int get_raw_temp_avg() {   
	int total = 0;
	int i;
	for (i = 0; i < CONF_NUM_AVG_TEMP; i++) {
		total += raw_temp_array[i];
	}
	return total / CONF_NUM_AVG_TEMP;
}


// Offset to real temperature
void sensor_set_real_temp(int temp) {
	sensor_offset = temp - adc10_sample_temp();	
	flash_save_config();
}
int sensor_get_real_temp() {
	return adc10_sample_temp() + sensor_offset;
}
int sensor_get_real_temp_avg() {
	return get_raw_temp_avg() + sensor_offset;
}


void sensor_init() {
	
    /* Temperature array init */
    init_raw_temp_array(0);
    
    TIMER_CAPTURE = 0;
	TIMER_GENERATE = 0;
}




PT_THREAD(thread_sensor(struct pt *pt)) {
    PT_BEGIN(pt);
    static int count;
    static temp_data data;

    while(1) {
    
        PT_WAIT_UNTIL(pt, TIMER_GENERATE >= CONF_GENERATE_PERIOD && node_id > 0); // node id 0 is for sink
        TIMER_GENERATE -= CONF_GENERATE_PERIOD; // restart timer in exactly CONF_GENERATE_PERIOD
        
        // turn sensor on and sample CONF_NUM_AVG_TEMP temp for average
        count = 0;
        while (count < CONF_NUM_AVG_TEMP) {
		    PT_WAIT_UNTIL(pt, TIMER_CAPTURE >= CONF_CAPTURE_PERIOD);
		    TIMER_CAPTURE -= CONF_CAPTURE_PERIOD;
		    add_raw_temp(adc10_sample_temp());
		    count++;
        }
        data.source = node_id;
        sensor_data_counter++;
        flash_save_config();
        data.packet_number = sensor_data_counter;
        data.temp = sensor_get_real_temp_avg();
        // try every cycle to append data to tx queue 
        PT_WAIT_UNTIL(pt, xmac_tx_append(data) == 0);// wait until msg has been appended
        if (verbocity) printf("\r\nNew message generated");
    }
    PT_END(pt);
}

